package com.ad.pet.app.login;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.ad.pet.R;
import com.ad.pet.app.RxDisposable;
import com.ad.pet.app.login.adapter.CharAdapter;
import com.ad.pet.app.login.adapter.CountryAdapter;
import com.ad.pet.common.data.injector.HasComponent;
import com.ad.pet.common.structure.mvp.BasePresenter;
import com.ad.pet.common.structure.ui.activity.AppToolbarActivity;
import com.ad.pet.models.remote.login.CategroyCountry;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;

/**
 * Created by SEELE on 2018/3/21.
 */

public class ChoseCountryActivity extends AppToolbarActivity implements ChoseCountryContract.View, HasComponent<LoginComponet> {
    @BindView(R.id.recycler_country)
    RecyclerView mRecyclerCountry;
    @BindView(R.id.recycler_char)
    RecyclerView mRecyclerChar;
    private CountryAdapter mCountryAdapter;
    LoginComponet mCircularComponent;

    @Inject
    ChoseCountryPresenter mPresenter;
    private Character[] mCharacters = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
    private CharAdapter mCharAdapter;
    private LinearLayoutManager mCountryLayoutManger;
    private List<CategroyCountry> mCountrys;

    @Inject
    RxDisposable mRxDisposable;
    private RxPermissions mRxPermissions;


    private String longTiue = "121.48";
    private String lenTiue = "31.22";
    private String locationProvider;
    private LocationManager locationManager;

    @Override
    protected void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);
        setToolbarTitle(getString(R.string.chose_country));
        mStatusLayoutManager.showContent();
    }

    @Override
    protected int contentLayout() {
        return R.layout.activity_chose_country;
    }

    @Override
    protected void clickRetry(View v) {

    }

    @Override
    protected void initViews() {
        mPresenter.onCreate(this);
        mRxPermissions = new RxPermissions(this);
    }

    @Override
    protected void initData() {


        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        List<String> providers = locationManager.getProviders(true);


        if (providers.contains(LocationManager.GPS_PROVIDER)) {
            //如果是GPS
            locationProvider = LocationManager.GPS_PROVIDER;
        } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
            //如果是Network
            locationProvider = LocationManager.NETWORK_PROVIDER;
        }
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        }else {
            Location location = locationManager.getLastKnownLocation(locationProvider);
            if (location != null) {
                longTiue = location.getLongitude()+"";
                lenTiue  = location.getLatitude()+"";
            }
        }

        mCountrys = new ArrayList<>();
        mPresenter.getCountry(longTiue,lenTiue);


        mCountryAdapter = new CountryAdapter(mCountrys);
        mCountryLayoutManger = new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false);
        mRecyclerCountry.setLayoutManager(mCountryLayoutManger);
//        mRecyclerCountry.addItemDecoration(new SimpleDividerDecoration(mActivity, 2, R.color.bg_color));
        mRecyclerCountry.setAdapter(mCountryAdapter);

        mCharAdapter = new CharAdapter(Arrays.asList(mCharacters));
        mRecyclerChar.setLayoutManager(new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false));
        mRecyclerChar.setAdapter(mCharAdapter);


    }

    @Override
    protected void initEvents() {
        mCharAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (mCountrys != null) {
//                    smoothMoveToPosition(mRecyclerCountry,mCountryAdapter.getScrollPosition(mCharacters[position]+""));
//                    mRecyclerCountry.smoothScrollToPosition(mCountryAdapter.getScrollPosition(mCharacters[position]+""));
                    mCountryLayoutManger.scrollToPositionWithOffset(mCountryAdapter.getScrollPosition(mCharacters[position] + ""), 0);
                    mCharAdapter.setClickLabel(position);
                }
            }
        });

//        mCountryAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
//            @Override
//            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                if (mCountrys != null) {
//                    Intent intent = new Intent();
//                    intent.putExtra("country", mCountrys.get(position));
//                    setResult(RESULT_OK, intent);
//                    finish();
//                }
//            }
//        });

        mCountryAdapter.setOnItemSelectCityLinstener(new CountryAdapter.OnItemSelectCityLinstener() {
            @Override
            public void onItemClick(int location, int position) {
                if (mCountrys != null) {
                    Intent intent = new Intent();
                    intent.putExtra("country", mCountrys.get(location).getList().get(position));
                    setResult(RESULT_OK, intent);
                    finish();
                }
            }
        });
    }

    @Override
    public void initInject() {
        mCircularComponent = DaggerLoginComponet.builder().applicationComponent(getApplicationComponent()).activityModule(getActivityModule()).build();
        mCircularComponent.inject(this);
    }

    @Override
    protected BasePresenter getPresenter() {
        return mPresenter;
    }

    @Override
    public LoginComponet getComponent() {
        return mCircularComponent;
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void error(String msg) {

    }


    @Override
    public void getCountrySuccess(List<CategroyCountry> list) {
//        Collections.sort(list,new ContactComparator());
        mCountrys.addAll(list);
        mCountryAdapter.notifyDataSetChanged();

    }

    /**
     * 目标项是否在最后一个可见项之后
     */
    private boolean mShouldScroll;
    /**
     * 记录目标项位置
     */
    private int mToPosition;

    private void smoothMoveToPosition(RecyclerView mRecyclerView, final int position) {
        // 第一个可见位置
        int firstItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(0));
        // 最后一个可见位置
        int lastItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(mRecyclerView.getChildCount() - 1));

        if (position < firstItem) {
            // 如果跳转位置在第一个可见位置之前，就smoothScrollToPosition可以直接跳转
            mRecyclerView.smoothScrollToPosition(position);
        } else if (position <= lastItem) {
            // 跳转位置在第一个可见项之后，最后一个可见项之前
            // smoothScrollToPosition根本不会动，此时调用smoothScrollBy来滑动到指定位置
            int movePosition = position - firstItem;
            if (movePosition >= 0 && movePosition < mRecyclerView.getChildCount()) {
                int top = mRecyclerView.getChildAt(movePosition).getTop();
                mRecyclerView.smoothScrollBy(0, top);
            }
        } else {
            // 如果要跳转的位置在最后可见项之后，则先调用smoothScrollToPosition将要跳转的位置滚动到可见位置
            // 再通过onScrollStateChanged控制再次调用smoothMoveToPosition，执行上一个判断中的方法
            mRecyclerView.smoothScrollToPosition(position);
            mToPosition = position;
            mShouldScroll = true;
        }
    }


}
